<template>
    <div class="tabs-wrapper">
      <el-tabs
        v-model="activeTab"
        type="card"
        closable
        @tab-remove="removeTab"
        @tab-click="handleClick"
        class="custom-tabs"
      >
        <el-tab-pane
          v-for="item in tabList"
          :key="item.path"
          :label="item.meta.title"
          :name="item.path"
          :closable="item.path !== '/homePage'"
        >
          <router-view v-if="activeTab === item.path" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </template>
  
  <script>
  export default {
    name: 'TabsView',
    data() {
      return {
        tabList: [
          {
            path: '/homePage',
            meta: { title: '首页' }
          }
        ],
        activeTab: '/homePage'
      }
    },
    watch: {
      $route: {
        immediate: true,
        handler(to) {
          this.activeTab = to.path
          const exists = this.tabList.find(tab => tab.path === to.path)
          if (!exists) {
            this.tabList.push({
              path: to.path,
              meta: to.meta || { title: to.name || '未命名' }
            })
          }
        }
      }
    },
    methods: {
      handleClick(tab) {
        if (tab.name !== this.$route.path) {
          this.$router.push(tab.name)
        }
      },
      removeTab(targetName) {
        const index = this.tabList.findIndex(tab => tab.path === targetName)
        this.tabList.splice(index, 1)
  
        // 切换到前一个或第一个 tab
        if (this.activeTab === targetName) {
          const nextTab = this.tabList[index - 1] || this.tabList[0]
          this.$router.push(nextTab.path)
        }
      }
    }
  }
  </script>
  
  <style scoped>
 
  </style>
  